  <!-- 显示员工详细信息，同时兼有导入，修改的作用 -->
<template>
  <el-dialog
    title="员工信息详情"
    :visible.sync="yuangongDialogVisible"
    :before-close="closeDialog"
    :fullscreen="true"
    style="text-align: center;"
  >
    <!-- 展示员工详细信息的表单 -->
    <el-form
      :model="yuangongForm"
      ref="yuangongFormRef"
      :rules="yuangongFormRules"
      class="yuangong"
    >
      <h2 class="jichu">基础信息</h2>
      <div class="user-left">
        <el-form-item
          label="姓名"
          size="normal"
          prop="name"
          class="name"
        >
          <el-input
            v-model="yuangongForm.name"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="性别"
          size="normal"
          prop="gender"
          class="gender"
        >
          <el-input
            v-model="yuangongForm.gender"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
      </div>
      <div class="user-right">
        <el-form-item
          label="头像"
          size="normal"
          prop="icon"
          class="icon"
        >
          <div class="upload">
            <el-upload
              class="avatar-uploader"
              :action="qiniu.action"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="upAvatarQiniu"
            >
              <img
                v-if="yuangongForm.avatar"
                :src="yuangongForm.avatar"
                class="avatar"
              >
              <img
                v-else
                src="http://qiniu.mdashen.com/defaultAvatar.jpg"
                class="avatar"
              >
              <!-- TODO hover提示上传头像 -->
            </el-upload>
          </div>
        </el-form-item>
      </div>
      <el-form-item
        label="年龄"
        size="normal"
        prop="age"
        class="age"
      >
        <el-input
          v-model="yuangongForm.age"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="身份证号码"
        size="normal"
        prop="idcard"
        class="idcard"
      >
        <el-input
          v-model="yuangongForm.idcard"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="籍贯"
        size="normal"
        prop="jiguan"
        class="jiguan"
      >
        <el-input
          v-model="yuangongForm.jiguan"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="家庭住址"
        size="normal"
        prop="address"
        class="address"
      >
        <el-input
          v-model="yuangongForm.address"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="毕业院校"
        size="normal"
        prop="school"
        class="school"
      >
        <el-input
          v-model="yuangongForm.school"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="学历"
        size="normal"
        prop="xueli"
        class="xueli"
      >
        <el-input
          v-model="yuangongForm.xueli"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <h2 class="renshi">人事信息</h2>
      <el-form-item
        label="入司时间"
        size="normal"
        prop="enterdata"
        v-if="!isAdd"
        class="enterdata"
      >
        <el-input
          v-model="yuangongForm.enterdata"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="离职时间"
        size="normal"
        prop="outdata"
        v-if="!isAdd"
        class="outdata"
      >
        <el-input
          v-model="yuangongForm.outdata"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="部门"
        size="normal"
        prop="bumen"
        class="bumen"
      >
        <el-input
          v-model="yuangongForm.bumen"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="岗位"
        size="normal"
        prop="gangwei"
        class="gangwei"
      >
        <el-input
          v-model="yuangongForm.gangwei"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="类别"
        size="normal"
        prop="category"
        class="category"
      >
        <el-input
          v-model="yuangongForm.category"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="人员定级"
        size="normal"
        prop="grade"
        class="grade"
      >
        <el-input
          v-model="yuangongForm.grade"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        label="工作地点"
        size="normal"
        prop="workaddr"
        class="workaddr"
      >
        <el-input
          v-model="yuangongForm.workaddr"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="footer">
      <span slot="footer">
        <el-button @click="setYuangongDialogVisible(false)">
          <span v-if="isAdd">取消录入</span>
          <span v-else>取消修改</span>
        </el-button>
        <el-button
          type="primary"
          @click="checkYg('yuangongFormRef')"
        >
          <span v-if="isAdd">录入</span>
          <span v-else>修改</span>
        </el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script>
import { homeMixin } from '../../utils/mixin'
export default {
  mixins: [homeMixin],
  data () {
    return {
      // 员工详情表格的校验规则，现在只加了不能为空的校验
      // TODO 以后可以完善更多的校验规则，如年龄不能为负，身份证号码校验等等
      yuangongFormRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请输入性别', trigger: 'blur' }],
        age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        idcard: [{ required: true, message: '请输入身份证号码', trigger: 'blur' }],
        jiguan: [{ required: true, message: '请输入籍贯', trigger: 'blur' }],
        address: [{ required: true, message: '请输入家庭住址', trigger: 'blur' }],
        school: [{ required: true, message: '请输入毕业院校', trigger: 'blur' }],
        xueli: [{ required: true, message: '请输入学历', trigger: 'blur' }],
        enterdata: [{ required: true, message: '请输入入司时间', trigger: 'blur' }],
        bumen: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        gangwei: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
        category: [{ required: true, message: '请输入类别', trigger: 'blur' }],
        grade: [{ required: true, message: '请输入定级', trigger: 'blur' }],
        workaddr: [{ required: true, message: '请输入工作地点', trigger: 'blur' }]
      },
      avatarUrl: '',
      // 七牛云相关
      qiniu: {
        // 上传地址，华南服务器
        action: 'https://upload-z2.qiniup.com',
        // 外链域名
        qiniuaddr: 'qiniu.mdashen.com',
        // 对象存储，空间名称
        bucketName: 'yishen_photos'
      }
    }
  },
  methods: {
    // 检验员工信息表格填写是否符合规则
    checkYg (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addOrUpdateYz()
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    // 新增或修改员工信息
    async addOrUpdateYz () {
      console.log(this.yuangongForm)
      const {
        name,
        gender,
        age,
        avatar,
        idcard,
        jiguan,
        address,
        school,
        xueli,
        enterdata,
        outdata,
        bumen,
        gangwei,
        category,
        grade,
        workaddr
      } = this.yuangongForm
      // 按下修改信息的按钮
      console.log(avatar)
      if (!this.isAdd) {
        // 更新数据
        const res = await this.$http.post('/yg/update', {
          id: this.yuangongForm.id,
          name,
          gender,
          age,
          avatar,
          idcard,
          jiguan,
          address,
          school,
          xueli,
          enterdata,
          outdata,
          bumen,
          gangwei,
          category,
          grade,
          workaddr
        })
        if (res.data.error_code === 0) {
          this.$message.success(res.data.msg)
          // TODO 更新this.ygList中的数据，添加记录后也要更新数据
          // this.setYuangongForm()
          this.setYuangongDialogVisible(false)
        }
      } else {
        // 新增员工
        console.log('新增员工')
        const res = await this.$http.post('/yg/add', {
          name,
          gender,
          age,
          avatar,
          idcard,
          jiguan,
          address,
          school,
          xueli,
          bumen,
          gangwei,
          category,
          grade,
          workaddr
        })
        console.log(res.data)
        if (res.data.error_code === 0) {
          this.$message.success('新增员工信息成功')
          this.setYuangongDialogVisible(false)
        } else {
          this.$message.error('失败')
        }
      }
    },
    // 关闭前询问用户，是否关闭，避免错误关闭
    closeDialog () {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.setYuangongDialogVisible(false)
        })
        .catch(_ => { })
    },
    // 头像上传前的钩子
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async getUpImgToken () {
      let token = sessionStorage.getItem('upAvatarToken')
      if (!token) {
        console.log('333')
        const { data } = await this.$http.get('/qiniu/token')
        if (data.error_code !== 0) {
          this.$message.error('上传失败!')
          return
        }
        token = data.data
        sessionStorage.setItem('upAvatarToken', token)
      }
      return token
    },
    // 头像上传实现
    async upAvatarQiniu (req) {
      // BUG 没有做上传限制，理论上，可以无限上传，被人当图床用。
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      let filetype = ''
      if (req.file.type === 'image/png') {
        filetype = 'png'
      }
      if (req.file.type === 'image/jpeg') {
        filetype = 'jpg'
      }
      // 重命名要上传的文件
      const keyname = 'pms_avatar_' + new Date().getTime() + '_' + Math.floor(Math.random() * 100) + '.' + filetype
      const token = await this.getUpImgToken()
      const formdata = new FormData()
      formdata.append('file', req.file)
      formdata.append('token', token)
      formdata.append('key', keyname)
      // 文件上传到七牛云空间
      try {
        var upImgRes = await this.$http.post(this.qiniu.action, formdata, config)
      } catch (error) {
        // 上传失败，可能是token过期
        sessionStorage.removeItem('upAvatarToken')
        this.$message.error('上传失败，请重新上传!')
        return
      }
      const avatar = 'https://' + this.qiniu.qiniuaddr + '/' + upImgRes.data.key
      this.setYuangongForm({ ...this.yuangongForm, avatar })
    }
  }
}
</script>

<style lang="scss" scoped>
@media screen and (max-width: 1800px) {
  .yuangong {
    width: 750px;
    margin: 0 auto;
  }
}

.yuangong {
  width: 800px;
  margin: 0 auto;
  border: 1px solid #000;
  overflow: hidden;
  margin-bottom: 10px;
  .jichu,
  .renshi {
    font-size: 18px;
    float: left;
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-bottom: 1px solid #000;
  }
  .renshi {
    border-top: 1px solid #000;
  }
  .el-form-item {
    display: flex;
    float: left;
  }

  .user-left {
    float: left;
    width: 50%;
  }

  .user-right {
    float: left;
  }
  .name,
  .gender {
    width: 100%;
  }
  .icon {
    img {
      margin-left: 20px;
      width: 100%;
      width: 100px;
      height: 130px;
    }
  }
  .name,
  .gender,
  .age,
  .jiguan,
  .school {
    margin-top: 10px;
    margin-left: 10px;
  }
  .gender /deep/.el-input__inner,
  .age /deep/.el-input__inner,
  .jiguan /deep/.el-input__inner,
  .name /deep/.el-input__inner {
    margin-left: 28px;
    width: 218px;
  }

  .idcard,
  .address,
  .xueli {
    margin-top: 10px;
    margin-left: 100px;
  }

  .xueli /deep/.el-input__inner {
    margin-left: 43px;
    width: 218px;
  }
  .grade /deep/.el-input__inner,
  .address /deep/.el-input__inner {
    margin-left: 14px;
    width: 218px;
  }

  .workaddr,
  .category,
  .bumen,
  .enterdata {
    margin-top: 10px;
    margin-left: 10px;
  }
  .category /deep/.el-input__inner,
  .bumen /deep/.el-input__inner {
    margin-left: 28px;
    width: 218px;
  }
  .grade,
  .gangwei,
  .outdata {
    margin-top: 10px;
    margin-left: 100px;
  }
  .outdata /deep/.el-input__inner {
    margin-left: 25px;
    width: 218px;
  }

  .gangwei /deep/.el-input__inner {
    margin-left: 41px;
    width: 218px;
  }
}
.footer {
  margin-left: 627px;
}
</style>
